package ipebg.mzk.provider.system.dao;

import ipebg.mzk.common.core.dao.impl.DBDao;
import ipebg.mzk.common.util.StringUtils;
import ipebg.mzk.facade.entity.MsAdminFunction;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

@Repository("functionDao")
public class FunctionDao extends DBDao<MsAdminFunction> {

	public FunctionDao(){
		super(MsAdminFunction.class);
	}
	
	
	public List<MsAdminFunction> findFunctionListByUserId(String userId){
		List list = null;
		List<MsAdminFunction> functionList = null;
		String selectSql = "   select DISTINCT cmf.FUNCTIONID,cmf.FUNCTIONCODE,cmf.FUNCTIONNAME from MS_FUNCTION cmf ";
		selectSql += " join MS_FUNCTION_ROLE rmr on(rmr.FUNCTIONID=cmf.FUNCTIONID ";
		selectSql += " and rmr.ROLEID in(";
		selectSql += "  select DISTINCT cmr.ROLEID from MS_ROLE cmr ";
		selectSql += "  JOIN MS_USERROLE rmu on(rmu.ROLEID=cmr.ROLEID) ";
		selectSql += " join MS_USER cmu on(cmu.adminid=rmu.ADMINID) ";
		selectSql += "  and cmu.adminid='" + userId + "'  union   select r.roleid  from MS_ROLE r where r.rolecode ='ROLE_NORMAL_SIGN_USER'))";

		String selectHql = "from MsAdminFunction f where f.functionId in(?)";
		try {
			List<String> fuctionIdList = new ArrayList<String>();
			list = findBySQL(selectSql, null);
			if (list != null && list.size() > 0) {				
				for (int i = 0; i < list.size(); i++) {
					Object[] obj = (Object[]) list.get(i);
					fuctionIdList.add(obj[0].toString());
				}
			}
			String functionIds = StringUtils.SqlFormatConvert(fuctionIdList);
			selectHql=selectHql.replace("?", functionIds);
			functionList=queryForList(selectHql, null);
			
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		return functionList;
	}
}
